<template>
  <div
    class="app-container"
    style="display: flex;flex-direction: row;justify-content: space-between;"
  >
    <!--左侧公司树图-->
    <div class="leftContent">
      <el-input
        style="margin-bottom: 10px"
        size="mini"
        placeholder="请输入分公司名称"
        v-model="filterText"
      >
      </el-input>
      <el-tree
        class="filter-tree"
        :data="treeData"
        :props="defaultProps"
        default-expand-all
        :filter-node-method="filterNode"
        @node-click="nodeClick"
        ref="tree"
      >
      </el-tree>
    </div>
    <!--右侧内容-->
    <div
      style="width: 85%;height: calc(100vh - 100px);background: white;overflow: auto"
    >
      <div class="filter-container" style="padding: 10px 20px">
        <!--右侧顶部查询条件-->
        <div style="margin-top: 15px">
          <el-form
            :inline="true"
            :model="listQuery"
            size="small"
            label-width="auto"
          >
            <el-form-item prop="keyword" label="账号：">
              <el-input
                placeholder="请输入用户账号"
                v-model="listQuery.username"
              ></el-input>
            </el-form-item>
            <el-form-item prop="nickName" label="姓名：">
              <el-input
                placeholder="请输入用户姓名"
                v-model="listQuery.nickName"
              ></el-input>
            </el-form-item>
            <el-form-item prop="phoneNumber" label="手机号：">
              <el-input
                placeholder="请输入手机号"
                v-model="listQuery.phoneNumber"
              ></el-input>
            </el-form-item>
            <el-form-item prop="status" label="状态：">
              <el-select
                v-model="listQuery.status"
                placeholder="请选择用户状态"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                style="float: right"
                type="primary"
                icon="el-icon-search"
                @click="handleSearchList()"
                size="small"
                v-debounce="1500"
                >查询</el-button
              >
              <el-button
                style="float: right; margin-right: 15px"
                icon="el-icon-refresh"
                @click="handleResetSearch()"
                size="small"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <!---->
        <div style="margin: 10px 0;">
          <el-button
            v-btnpermission="$btnPer.adminBtnrules.addAdmin"
            @click="handleAdd()"
            size="small"
            type="primary"
            ><i class="el-icon-circle-plus-outline"></i> 添加用户</el-button
          >
          <el-button
            v-btnpermission="$btnPer.adminBtnrules.batchDelete"
            size="small"
            type="primary"
            @click="deleteAdminList"
            ><i class="el-icon-delete"></i> 批量删除</el-button
          >
        </div>
        <!--查询列表-->
        <div class="table-container">
          <el-table
            ref="adminTable"
            :data="list"
            style="width: 100%"
            v-loading="listLoading"
            @selection-change="selectTableList"
            border
          >
            <el-table-column type="selection" width="40"></el-table-column>
            <el-table-column
              label="编号"
              width="100"
              align="center"
              type="index"
            ></el-table-column>
            <el-table-column
              label="帐号"
              align="center"
              prop="username"
            ></el-table-column>
            <el-table-column
              label="姓名"
              align="center"
              prop="nickName"
            ></el-table-column>
            <el-table-column
              label="所属分公司"
              align="center"
              prop="deptName"
            ></el-table-column>
            <el-table-column
              label="手机号"
              align="center"
              prop="phoneNumber"
            ></el-table-column>
            <el-table-column width="200px" label="角色" align="center">
              <template slot-scope="scope">
                <el-tag
                  size="mini"
                  v-for="item in scope.row.roleList"
                  :key="item.roleId"
                  type="success"
                  >{{ item.name }}</el-tag
                >
              </template>
            </el-table-column>
            <!--<el-table-column label="邮箱" align="center" prop="email"></el-table-column>-->
            <el-table-column
              label="添加时间"
              width="160"
              align="center"
              prop="createTime"
            ></el-table-column>
            <!--<el-table-column label="添加时间" width="160" align="center" prop="createTime">-->
            <!--  <template slot-scope="scope">{{ scope.row.createTime | formatDateTime }}</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="最后登录" width="160" align="center">-->
            <!--  <template slot-scope="scope">{{-->
            <!--      scope.row.loginTime | formatDateTime-->
            <!--    }}</template>-->
            <!--</el-table-column>-->
            <!-- v-btnpermission="$btnPer.adminBtnrules.editStatusUser" -->
            <el-table-column label="是否启用" width="140" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-btnpermission="$btnPer.adminBtnrules.editStatusUser"
                  @change="handleStatusChange(scope.$index, scope.row)"
                  :active-value="1"
                  :inactive-value="0"
                  v-model="scope.row.status"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="scope">
                <el-button
                  v-btnpermission="$btnPer.adminBtnrules.relationRole"
                  size="mini"
                  type="text"
                  v-if="scope.row.adminId !== 1"
                  @click="handleSelectRole(scope.$index, scope.row)"
                  >分配角色</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  :disabled="name !== 'admin' && scope.row.adminId == 1"
                  @click="handleUpdate(scope.$index, scope.row)"
                  v-btnpermission="$btnPer.adminBtnrules.editAdmin"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  v-if="scope.row.adminId !== 1"
                  @click="handleDelete(scope.$index, scope.row)"
                  v-btnpermission="$btnPer.adminBtnrules.deleteAdmin"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--分页-->
        <div class="pagination-container" style="padding-bottom: 20px">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="listQuery.pageNum"
            :page-size="listQuery.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!--添加用户弹框-->
    <addUser
      ref="addUserForm"
      :isEdit="isEdit"
      :dialogVisible="dialogVisible"
      @cancleDialog="cancleFun"
    ></addUser>
    <!--分配角色弹框-->
    <el-dialog title="分配角色" :visible.sync="allocDialogVisible" width="30%">
      <el-select
        v-model="allocRoleIds"
        multiple
        placeholder="请选择"
        size="small"
        style="width: 80%"
      >
        <el-option
          v-for="item in allRoleList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocDialogVisible = false" size="small"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="handleAllocDialogConfirm()"
          size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import {
  fetchList,
  updateStatus,
  deleteAdmin,
  getRoleByAdmin,
  allocRole
} from "@/api/login";
import { fetchAllRoleList } from "@/api/role";
import { formatDate } from "@/utils/date";
import { treeList, deleteUserList } from "@/api/treeList";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import addUser from "./components/addUser.vue";
import { authPhone } from "@/utils/auth.js";
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  username: null,
  nickName: "",
  phoneNumber: "",
  status: ""
};
const defaultAdmin = {
  id: null,
  username: null,
  password: null,
  nickName: null,
  email: null,
  note: null,
  status: 1,
  phoneNumber: null
};
export default {
  name: "adminList",
  components: { Treeselect, addUser },
  computed: {
    ...mapGetters(["sidebar", "avatar", "name", "bgColor"])
  },
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery), //查询条件
      list: null, //查询列表数据
      total: null,
      listLoading: false, //查询数据列表加载loading状态
      dialogVisible: false, //添加用户弹框显示
      admin: Object.assign({}, defaultAdmin),
      isEdit: false, //编辑状态
      allocDialogVisible: false, //分配角色弹框
      allocRoleIds: [], //选择的角色数据
      allRoleList: [], //角色列表
      allocAdminId: null,
      filterText: "", //左侧筛选数据
      treeData: [], //左侧树图数据
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 搜索条件状态下拉数据
      options: [
        { value: "1", label: "启用" },
        { value: "0", label: "停用" }
      ],
      // 批量删除
      deleteList: [],
      // 部门树选项
      deptOptions: []
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();

    this.getTreeData();
  },
  filters: {
    formatDateTime(time) {
      if (time == null || time === "") {
        return "N/A";
      }
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  methods: {
    // 添加用户弹框取消按钮
    cancleFun(val) {
      this.dialogVisible = val;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 点击左侧公司树图
    nodeClick(data, node, self) {
      this.listLoading = true;
      this.listQuery.deptId = data.id;
      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
      });
    },
    // 获取公司树图数据
    getTreeData() {
      const params = {
        id: "",
        parentId: "",
        deptName: "",
        status: ""
      };
      treeList(params).then(res => {
        if (res.code === 200) {
          this.treeData = res.data;
        }
      });
    },
    // 重置查询条件
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    // 查询列表
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    async handleAdd() {
      // await this.getAllRoleList();
      await this.$refs.addUserForm.getAffilcation();
      this.dialogVisible = true;
      this.isEdit = false;
      this.admin = Object.assign({}, defaultAdmin);
    },
    // 列表中是否启用开关
    handleStatusChange(index, row) {
      this.$confirm("是否要修改该状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateStatus(row.adminId, { status: row.status }).then(response => {
            this.$message({
              type: "success",
              message: "修改成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消修改"
          });
          this.getList();
        });
    },
    // 删除按钮
    handleDelete(index, row) {
      this.$confirm("是否要删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteAdmin(row.adminId).then(response => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getList();
        });
      });
    },
    // 编辑信息
    handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      // this.admin = Object.assign({}, row);
      this.$refs.addUserForm.openlogin(row);
    },
    // 分配角色弹框确认按钮
    handleAllocDialogConfirm() {
      this.$confirm("是否要确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let params = new URLSearchParams();
        params.append("adminId", this.allocAdminId);
        params.append("roleIds", this.allocRoleIds);
        allocRole(params).then(response => {
          this.$message({
            message: "分配成功！",
            type: "success"
          });
          this.allocDialogVisible = false;
          this.getList();
        });
      });
    },
    // 点击分配角色按钮
    handleSelectRole(index, row) {
      this.allocAdminId = row.adminId;
      this.allocDialogVisible = true;
      this.getAllRoleList();
      this.getRoleListByAdmin(row.adminId);
    },
    // 获取用户列表数据
    getList() {
      if (
        this.listQuery.phoneNumber &&
        !authPhone(this.listQuery.phoneNumber)
      ) {
        return this.$message.error("请输入正确的手机号");
      }
      this.listLoading = true;
      fetchList(this.listQuery)
        .then(response => {
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 批量删除
    deleteAdminList() {
      if (this.deleteList.length > 0) {
        this.$confirm("是否确认批量删除选择的用户？", "提示", {
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
          .then(async () => {
            let res = await deleteUserList(this.deleteList);
            if (res.code === 200) {
              this.$message.success("删除成功！");
              this.getList();
            }
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      } else {
        this.$message.error("请选择要删除的数据");
      }
    },
    selectTableList(val) {
      this.deleteList = val.map(v => v.adminId);
    },
    getAllRoleList() {
      fetchAllRoleList().then(response => {
        this.allRoleList = response.data;
      });
    },
    getRoleListByAdmin(adminId) {
      getRoleByAdmin(adminId).then(response => {
        let allocRoleList = response.data;
        this.allocRoleIds = [];
        if (allocRoleList != null && allocRoleList.length > 0) {
          for (let i = 0; i < allocRoleList.length; i++) {
            this.allocRoleIds.push(allocRoleList[i].id);
          }
        }
      });
    }
  }
};
</script>
<style scoped>
.app-container {
  background-color: #f5f5f5;
}
.leftContent {
  margin-right: 10px;
  width: 15%;
  height: calc(100vh - 100px);
  overflow: auto;
  background: white;
  padding: 20px 10px;
}
</style>
